#include "tablewriter.h"
#include "datatable.h"

#include <QFile>
#include <QTextStream>
#include <QDebug>

class TableWriterPrivate
{
public:
    QString file;
    QList<TableData*> dataTables;
};

TableWriter::TableWriter()
{
    d_ptr = new TableWriterPrivate;
}

TableWriter::~TableWriter()
{
    delete d_ptr;
}

void TableWriter::setFileName(const QString& file)
{
    d_ptr->file = file;
}

QString TableWriter::fileName() const
{
    return d_ptr->file;
}

void TableWriter::addTableData(TableData *td)
{
    if (td)
        d_ptr->dataTables.append(td);
}

void TableWriter::run()
{
    if (d_ptr->dataTables.isEmpty() || d_ptr->file.isEmpty())
        return;

    QFile file(d_ptr->file);
    if (!file.open(QIODevice::WriteOnly))
        return;

    QFile styleFile(":./style.css");
    if (!styleFile.open(QIODevice::ReadOnly))
        qDebug() << "failed to read html style file.";
    QString style = styleFile.readAll();

    QFile scriptFile(":./dt.js");
    if (!scriptFile.open(QIODevice::ReadOnly))
        qDebug() << "failed to read script file.";
    QString script = scriptFile.readAll();

    const QString header = "\n<!DOCTYPE html><html><head>"
                    "<style>"  + style  + "</style></head><body>";

    const QString footer = "<script src=\"http://libs.baidu.com/jquery/1.9.1/jquery.min.js\"></script><script>"
                            + script + "</script></body></html>";

    QTextStream ts(&file);
    ts << header;
    ts << "<div id=\"tabs-wrapper\">";
    // write tabs
    for (int i = 0; i < d_ptr->dataTables.size(); ++i) {
        QString tableName = d_ptr->dataTables.at(i)->name();
        QString tableNameId = d_ptr->dataTables.at(i)->name().replace(' ', '_');
        qDebug() << "table name" << tableName;
        ts << QString("<a href=\"#%1\"><div class=\"tab\">%2</div></a>").arg(tableNameId).arg(tableName);
    }

    ts << "</div>";

    for (int tableIndex = 0; tableIndex < d_ptr->dataTables.size(); ++tableIndex) {
        auto table = d_ptr->dataTables.at(tableIndex);

        ts << QString("<div id=\"%1\" class=\"mytabs\">").arg(table->name().replace(' ', '_'));

        ts << "<table class=\"bordered scrollTable\"><thead class=\"fixedHeader\"><tr>";
        QStringList horLabels = d_ptr->dataTables.at(tableIndex)->labels(Qt::Horizontal);
        for (int labelIndex = 0; labelIndex < horLabels.size(); ++labelIndex)
            ts << QString("<th>%1</th>").arg(horLabels.at(labelIndex));
        ts << "</tr></thead><tbody class=\"scrollContent\">";

        QString str;
        for (int rowIndex = 0; rowIndex < table->rows(); ++rowIndex) {
            ts << "<tr>";
            for (int colIndex = 0; colIndex < table->cols(); ++colIndex) {
                str = table->data(colIndex, rowIndex);
                ts << "<td>" << str << "</td>";
            }
            ts << "</tr>";
        }

        ts << "</tbody></table></div>";
    }
    ts << footer;
}
